export class LocalKey {
  static appToken: string = 'app_token';
  static refreshToken: string = 'refresh_token';
  static qiNiuToken: string = 'qi_niu_token';
}

interface LocalType {
  value: string;
  expired: number;
  timeOut: number;
}

export class Local {
  /**
   * 获取字符串
   * @param key
   * @param defaultValue 默认值
   */
  public static getStr(key: string, defaultValue?: string): string | undefined {
    let value = localStorage.getItem(key);
    if (value === null) {
      return defaultValue === undefined ? undefined : defaultValue;
    }
    try {
      const obj = JSON.parse(value);
      if (obj.expired === 0) {
        return obj.value;
      }
      if (Local.isTimeOut(obj.timeOut)) {
        localStorage.removeItem(key);
        return defaultValue === undefined ? undefined : defaultValue;
      }
      return obj.value;
    } catch (e) {
      return value;
    }
  }

  /**
   * 设置str
   * @param key key
   * @param value 值
   * @param expired 秒数
   */
  public static setStr(key: string, value: string, expired = 0): void {
    if (expired === 0) {
      const jsonValue = JSON.stringify({
        value: value,
        expired: expired,
        timeOut: -1,
      });
      localStorage.setItem(key, jsonValue);
    } else {
      const timeOut = new Date().valueOf() + expired * 1000;
      const jsonValue = JSON.stringify({
        value: value,
        expired: expired,
        timeOut: timeOut,
      });
      localStorage.setItem(key, jsonValue);
    }
  }

  public static get token() {
    const value = Local.getStr(LocalKey.appToken, undefined)!;
    if (value === undefined) {
      return undefined;
    }
    return value;
  }

  public static get refreshToken() {
    return Local.getStr(LocalKey.refreshToken, undefined)!;
  }

  /**
   * 获取是否过期
   * @param outTime
   * @private
   */
  private static isTimeOut(outTime: number) {
    const timeOut = new Date().valueOf();
    return timeOut > outTime;
  }
}
